<template>
  <div class="app-container">
    <div class="flex">
      <!-- <div class="left">
        <el-button @click="addCatelog" class="addCatelog">添加目录</el-button>
        <el-input placeholder="输入关键字进行过滤" v-model="filterText">
        </el-input>

        <el-tree
          class="filter-tree"
          ref="tree"
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          highlight-current
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        >
        </el-tree>
      </div> -->
      <div class="left">
        <div class="comp-tree">
          <el-button
            class="comp-tr-top"
            type="primary"
            size="small"
            @click="handleAddTop"
            style="width: auto;"
            >添加数据血缘目录</el-button
          >
          <!-- tree -->
          <el-tree
            ref="SlotTree"
            :data="treeList"
            :props="defaultProps"
            :current-node-key="currentNodekey"
            :expand-on-click-node="false"
            highlight-current
            :node-key="NODE_KEY"
            @node-click="handleNodeClick"
          >
            <div class="comp-tr-node" slot-scope="{ node, data }">
              <!-- 编辑状态 -->
              <template v-if="node.isEdit">
                <el-input
                  v-model="data.name"
                  autofocus
                  size="mini"
                  :ref="'slotTreeInput' + data[NODE_KEY]"
                  @blur.stop="handleInput(node, data)"
                  @keyup.enter.native="handleInput(node, data)"
                ></el-input>
              </template>

              <!-- 非编辑状态 -->
              <template v-else>
                <!-- 名称： 新增节点增加class（is-new） -->
                <span
                  :class="[
                    data[NODE_KEY] < NODE_ID_START ? 'is-new' : '',
                    'comp-tr-node--name'
                  ]"
                >
                  {{ node.label }}
                </span>

                <!-- 按钮 -->
                <el-dropdown placement="top" style="margin-left: 10%;">
                  <span class="el-dropdown-link">
                    <i class="el-icon-more el-icon--right"></i>
                  </span>
                  <el-dropdown-menu>
                    <!-- 新增 -->
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="添加子节点"
                      placement="top"
                    >
                      <el-button
                        icon="el-icon-plus"
                        size="large"
                        circle
                        title="添加子节点"
                        @click="handleAdd(node, data)"
                        style="
                          border: none;
                          background-color: transparent;
                          transform: scale(1.1);
                        "
                      ></el-button>
                    </el-tooltip>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="查看节点详情"
                      placement="top"
                    >
                      <!-- 查看 -->
                      <el-button
                        icon="el-icon-document"
                        size="large"
                        circle
                        title="查看节点详情"
                        @click="handleLook(node, data)"
                        style="
                          border: none;
                          background-color: transparent;
                          transform: scale(1.1);
                        "
                      ></el-button>
                    </el-tooltip>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="编辑节点"
                      placement="top"
                    >
                      <el-button
                        icon="el-icon-edit"
                        size="large"
                        circle
                        title="编辑节点"
                        @click="handleEdit(node, data)"
                        style="
                          border: none;
                          background-color: transparent;
                          transform: scale(1.1);
                        "
                      ></el-button>
                    </el-tooltip>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="删除节点"
                      placement="top"
                    >
                      <el-button
                        icon="el-icon-delete"
                        size="large"
                        circle
                        title="删除节点"
                        @click="handleDeletetree(node, data)"
                        style="
                          border: none;
                          background-color: transparent;
                          transform: scale(1.1);
                        "
                      ></el-button>
                    </el-tooltip>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </div>
          </el-tree>
        </div>
      </div>
      <div class="right">
        <div class="r-top">
          <el-button type="primary" @click="add" class="add"
            >新增血缘关系</el-button
          >
        </div>
        <div class="r-bottom">
          <div
            id="x6model"
            ref="graphContainer"
            style="width: 80vw; height: 100vh;"
          />
        </div>
      </div>
    </div>

    <!-- 新增的弹窗 -->
    <!-- :visible.sync="dialogFormVisible" -->
    <el-dialog
      title="新增血缘关系"
      :visible.sync="dialogFormVisible"
      v-if="dialogFormVisible"
    >
      <el-form :model="form">
        <el-form-item label="目录" :label-width="formLabelWidth">
          <el-select
            v-model="form.region"
            filterable
            placeholder="请选择目录"
            @change="selectChange"
          >
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input
            v-model="form.name"
            autocomplete="off"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            v-model="form.desc"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirmDialog">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 点击新增确定后弹窗 -->
    <child-modal
      v-if="modalVisible"
      :value="modalVisible"
      @update:value="handleModalVisible"
    ></child-modal>
    <treeData ref="treeForm" @getTreeList="getTreeList" />
  </div>
</template>

<script>
import { Graph } from '@antv/x6'
import ChildModal from './add/index.vue'
import treeData from './treeData.vue'
import {
  fetchMasterdataDirectoryList,
  deleteMasterdataDirectory
} from '@/api/masterdata/masterdataDirectory'
import { addMetaModel } from '@/api/dataKinship/index.js'
export default {
  name: 'SdssDatagovernanceFrontendIndex',
  components: {
    ChildModal,
    treeData
  },
  data() {
    return {
      graph: null,
      filterText: '',
      dialogFormVisible: false, //新增弹窗
      modalVisible: false, //确定新增后的弹窗
      form: {
        name: '',
        region: '',
        desc: ''
      },
      formLabelWidth: '100px',
      selectOptions: [],
      x6List: {
        cellList: [
          {
            tableId: '1746418493533818881',
            tableName: 'T_ST_DYZ_ZMKDSJCL',
            tableDescription: '打渔张泵站闸门开度数据处理表',
            x: 100,
            y: 100
          },
          {
            tableId: '1746418490614583298',
            tableName: 'T_D_STAT_LS_FB_RECORD',
            tableDescription: '泵站机组开关机记录表',
            x: 100,
            y: 300
          },
          {
            tableId: '1751844592089243650',
            tableName: 'T_ST_DYZ_EDGNBVFTTY',
            tableDescription: '根据15标数据统计来的',
            x: 100,
            y: 500
          },
          {
            tableId: '1751844591900499970',
            tableName: 'T_ST_DYZ_ZDKJITHHL',
            tableDescription: '棘洪滩水库闸门数据处理表',
            x: 500,
            y: 500
          }
        ],
        edgeList: [
          {
            sourceId: '1746418493533818881',
            sourceName: 'T_ST_DYZ_ZMKDSJCL',
            targetId: '1746418490614583298',
            targetName: 'T_D_STAT_LS_FB_RECORD',
            sourcePort: 'port3',
            targetPort: 'port1',
            sourceCell: null,
            targetCell: null
          },
          {
            sourceId: '1746418490614583298',
            sourceName: 'T_D_STAT_LS_FB_RECORD',
            targetId: '1751844592089243650',
            targetName: 'T_ST_DYZ_EDGNBVFTTY',
            sourcePort: 'port3',
            targetPort: 'port1',
            sourceCell: null,
            targetCell: null
          },
          {
            sourceId: '1751844592089243650',
            sourceName: 'T_ST_DYZ_EDGNBVFTTY',
            targetId: '1751844591900499970',
            targetName: 'T_ST_DYZ_ZDKJITHHL',
            sourcePort: 'port6',
            targetPort: 'port5',
            sourceCell: null,
            targetCell: null
          }
        ]
      },
      //x6数据
      //
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      currentNodekey: '',
      NODE_KEY: 'id',
      MAX_LEVEL: 5,
      listQuery: {
        type: '2',
        jobName: undefined,
        dbType: undefined,
        executeStatus: undefined,
        checkStatus: undefined,
        isSync: undefined,
        directoryId: '',
        page: 1,
        limit: this.$store.getters.defaultPageSize
      },
      startId: null,
      NODE_ID_START: 0,
      treeQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '11'
      },
      initParam: {
        // 新增参数
        name: '新增节点',
        parentId: 0,
        children: []
      }
    }
  },
  created() {
    this.getTreeList()
  },
  mounted() {
    this.getX6Echarts()
  },

  methods: {
    //树搜索
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    //下拉框点击
    selectChange(val) {
      // console.log(this.form, val, '下拉框点击的项')
    },
    //新增血缘关系
    add() {
      console.log('1111')
      this.dialogFormVisible = true
    },
    //取消
    closeDialog() {
      this.dialogFormVisible = false
      //需要手动清空form绑定的内容
    },
    //确定
    confirmDialog() {
      if (this.form.region == '' || this.form.name == '') {
        this.$message.error('目录或名称为空,不能提交!')
      } else {
        const params = {
          isDirectory: 1,
          parentId: this.form.region,
          name: this.form.name,
          description: this.form.desc,
          ancestralId: 11,
          id: null
        }
        addMetaModel(params).then((res) => {
          console.log(res, '提交试试')
          if (res.status == 200) {
            this.getTreeList()
            this.form = {
              name: '',
              region: '',
              desc: ''
            }
            this.$message.success('新增成功!')
            this.dialogFormVisible = false
            this.modalVisible = true
          } else {
            this.$message.error('新增失败!')
          }
        })
      }
      console.log(this.modalVisible)
    },
    handleModalVisible(value) {
      this.modalVisible = value
    },
    //x6初始化
    getX6Echarts() {
      if (this.graph) {
        this.graph.dispose()
      }
      const container = this.$refs.graphContainer
      this.graph = new Graph({
        container,
        panning: true, //画布是否可拖动
        interacting: false, //是否可交互
        connecting: {
          allowBlank: false,
          allowLoop: false
          // allowNode: false
        }
      })
      this.x6List.cellList.map((item) => {
        Graph.registerNode(
          'custom-node',
          {
            width: 200,
            height: 60,
            attrs: {
              body: {
                stroke: '#5F95FF',
                strokeWidth: 1,
                fill: 'rgba(95,149,255,0.05)',
                refWidth: 1,
                refHeight: 1
              },
              image: {
                'xlink:href':
                  'https://gw.alipayobjects.com/zos/antfincdn/FLrTNDvlna/antv.png',
                width: 16,
                height: 16,
                x: 12,
                y: 12
              },
              title: {
                text: '',
                refX: 40,
                refY: 14,
                fill: 'rgba(0,0,0,0.85)',
                fontSize: 12,
                'text-anchor': 'start'
              },
              text: {
                text: '',
                refX: 40,
                refY: 38,
                fontSize: 12,
                fill: 'rgba(0,0,0,0.6)',
                'text-anchor': 'start'
              }
            },
            markup: [
              {
                tagName: 'rect',
                selector: 'body'
              },
              {
                tagName: 'image',
                selector: 'image'
              },
              {
                tagName: 'text',
                selector: 'title'
              },
              {
                tagName: 'text',
                selector: 'text'
              }
            ]
          },
          true
        )
      })

      const newCellList = []
      this.x6List.cellList.map((v, i) => {
        const newCell = this.graph.addNode({
          x: v.x,
          y: v.y,
          width: 300,
          height: 60,
          shape: 'custom-node',
          data: {
            id: v.tableId,
            label: v.tableName
          },
          attrs: {
            title: {
              text: v.tableName
            },
            text: {
              text: v.tableDescription
            }
          },
          ports: {
            groups: {
              in: {
                position: 'top',
                attrs: {
                  circle: {
                    r: 6,
                    magnet: true,
                    stroke: '#31d0c6',
                    strokeWidth: 2,
                    fill: '#fff'
                  }
                }
              },
              out: {
                position: 'bottom',
                attrs: {
                  circle: {
                    r: 6,
                    magnet: true,
                    stroke: '#31d0c6',
                    strokeWidth: 2,
                    fill: '#fff'
                  }
                }
              },
              topLeft: {
                position: 'left',
                attrs: {
                  circle: {
                    r: 6,
                    magnet: true,
                    stroke: '#31d0c6',
                    strokeWidth: 2,
                    fill: '#fff'
                  }
                }
              },
              bottomRight: {
                position: 'right',
                attrs: {
                  circle: {
                    r: 6,
                    magnet: true,
                    stroke: '#31d0c6',
                    strokeWidth: 2,
                    fill: '#fff'
                  }
                }
              }
            },
            items: [
              {
                id: 'port1',
                group: 'in'
              },
              {
                id: 'port2',
                group: 'in'
              },
              {
                id: 'port3',
                group: 'out'
              },
              {
                id: 'port4',
                group: 'out'
              },
              {
                id: 'port5',
                group: 'topLeft'
              },
              {
                id: 'port6',
                group: 'bottomRight'
              }
            ]
          }
        })
        newCellList.push(newCell)
        // console.log(newCellList, '~~~newCellListnewCellListnewCellList')
      })

      this.x6List.edgeList.forEach((item) => {
        newCellList.forEach((newCellItem) => {
          if (item.sourceId === newCellItem.data.id) {
            item.sourceCell = newCellItem.id
          }
          if (item.targetId === newCellItem.data.id) {
            item.targetCell = newCellItem.id
          }
        })
      })

      // console.log(this.listArrray, 'hhhhhhhhhhh') // 处理后的数据将会显示出来

      this.x6List.edgeList.map((v, i) => {
        this.graph.addEdge({
          source: { cell: v.sourceCell, port: v.sourcePort },
          target: { cell: v.targetCell, port: v.targetPort }
          // ]
        })
      })
    },
    //树数据
    getTreeList() {
      this.listLoading = true
      fetchMasterdataDirectoryList(this.treeQuery).then((response) => {
        if (response.data.code == 200) {
          this.treeList = response.data.data
          console.log(this.treeList, 'treeListtreeList')
          this.selectOptions = this.transformTreeData(response.data.data)
          console.log(this.selectOptions, '处理后的selectOptionsselectOptions')
          if (this.treeList.length > 0) {
            this.listQuery.directoryId = this.treeList[0].children[0].id
            this.currentNodekey = this.treeList[0].id
            // this.getList()
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey) //一定要加这个选中了否则样式没有出来
            })
          }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    //树子项点击
    handleNodeClick(data) {
     
           this.listQuery.directoryId =data.id
      console.log(data, '点击了树形11')
      if (data.isDirectory == '0') {
        this.form.region = data.id
      } else {
        this.form.region = data.parentId
      }
    },
    // 修改节点
    handleInput(_node, _data) {
      console.log(_node, _data)

      // updateMasterdataDirectory(obj).then(res=>{
      //   if(res.data.code==0){
      //     this.$message.success(res.data.msg)
      //     this.getTreeList()
      //   }else{
      //     this.$message.error(res.data.msg)
      //   }
      // })
      // 退出编辑状态
      if (_node.isEdit) {
        this.$set(_node, 'isEdit', false)
      }
      this.getTreeList()
    },
    // 新增节点
    handleAdd(_node, _data) {
      console.log(_node, _data)
      // // 判断层级
      if (_node.level >= this.MAX_LEVEL) {
        this.$message.warning('当前已达到' + this.MAX_LEVEL + '级，无法新增！')
        return false
      }
      // 参数修改
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = _data.id // 父id
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      this.$refs.treeForm.handleCreate(obj, this.treeQuery.ancestralId)
      this.getTreeList()
    },
    handleLook(_node, _data) {
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description
      }
      this.$refs.treeForm.handleLook(obj, this.treeQuery.ancestralId)
    },
    // 编辑节点
    handleEdit(_node, _data) {
      console.log(_node, _data)
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description
      }
      this.$refs.treeForm.handleUpdate(obj, this.treeQuery.ancestralId)
      this.getTreeList()
    },
    // 删除节点
    handleDeletetree(_node, _data) {
      console.log(_node, _data)
      // 判断是否存在子节点
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可删除！')
        return false
      } else {
        // 删除操作
        let DeletOprate = () => {
          this.$nextTick(() => {
            if (this.$refs.SlotTree) {
              deleteMasterdataDirectory(_data.id).then((res) => {
                 
                this.$message.success('删除成功！')
                this.$refs.SlotTree.remove(_data)
                this.getTreeList()
              })
            }
          })
        }

        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此节点？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              DeletOprate()
              this.getTreeList()
            })
            .catch(() => {})
        }

        // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
        _data[this.NODE_KEY] < this.NODE_ID_START ? DeletOprate() : ConfirmFun()
      }
    },
    handleAddTop() {
      // 添加顶部节点
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = 0
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      // console.log(obj,'顶部参数')
      this.$refs.treeForm.handleCreate(obj, this.treeQuery.ancestralId)
      this.getTreeList()
    },
    //转化树形列表的数据
    transformTreeData(tree) {
      // 初始化一个空数组来收集选项
      let options = []

      tree.forEach((node) => {
        if (node.isDirectory === '0') {
          // 添加目录节点到选项中
          options.push({
            value: node.id,
            label: node.name
          })
          // 如果节点有子节点，递归调用并将结果附加到选项数组中
          if (node.children && node.children.length) {
            options = options.concat(this.transformTreeData(node.children))
          }
        }
      })

      return options
    }
  }
}
</script>

<style lang="scss" scoped>
.flex {
  width: 100%;
  height: 100%;
  display: flex;
}
.left {
  width: 18vw;
  height: 100%;
  margin-right: 1.5vw;
}
.right {
  width: 80vw;
}

#x6model {
  background-image: url('../../../../assets/dataRelationBg.png');
  background-size: cover;
}
.addCatelog {
  width: 100%;
}
.r-top {
  position: relative;
}
.add {
  position: absolute;
  right: 15%;
  top: 50%;
  z-index: 99;
}
</style>
